package com.yonyou.pmclouds.workconnect.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.annotation.Insert;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.service.CommonPropertiesProcessor;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.workConnect.entity.WorkConReceiverVO;
import com.yonyou.pmclouds.workConnect.entity.WorkConnectVO;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConReceiverMaintain;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConReceiverQuery;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConnectMaintain;
import com.yonyou.pmclouds.workConnect.service.rmiitf.WorkConnectQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工作联系接口
 */
@Slf4j
@Controller
@RequestMapping(value = {"/mobile/workconnect","/workconnect"})
public class WorkConnectController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkConnectQuery query;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkConnectMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkConReceiverMaintain receiverMaintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkConReceiverQuery receiverQuery;
    @Autowired
    private UserInfoQuery userQuery;
    @Autowired
    private CommonPropertiesProcessor propertiesProcessor;

    private static final String[] USER_ID_FIELDS = {WorkConnectVO.CREATOR};
    private static final String[] USER_NAME_FIELDS = {WorkConnectVO.CREATOR_NAME};

    /**
     * 方法描述：根据项目查询所有的工作联系单
     *
     * @param pk_project
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/queryByProject")
    @ResponseBody
    public AdditionalPropertiesVOWrapper[] queryByPkProject(String pk_project) throws BusinessException {
        List<WorkConnectVO> workConnectVOs = query.selectByPkProject(pk_project);
        if (workConnectVOs == null || workConnectVOs.size() == 0) {
            return null;
        }
        WorkConnectVO[] beans = workConnectVOs.toArray(new WorkConnectVO[0]);
        userQuery.tranUserInfoField(beans, USER_ID_FIELDS, USER_NAME_FIELDS);
        return propertiesProcessor.wrapAdditionalProps(beans);
    }

    /**
     * 添加工作联系
     * @param workConnectVO
     * @param response
     * @return
     * @throws BusinessException
     */
    @Insert
    @RequestMapping(value = "/add")
    @ResponseBody
    public WorkConnectVO add(@RequestBody WorkConnectVO workConnectVO,
                             HttpServletResponse response) throws BusinessException {
        //智能日志需要制单人信息
        String creatorName = userQuery.queryUserName(RuntimeEnvironment.getLoginUserId());
        workConnectVO.setCreator_name(creatorName);
        WorkConnectVO workConnect = maintain.addWorkConnect(workConnectVO);
        WorkConnectVO workConnectSelect = query.selectOne(workConnect.getPk_workconnect());
        wrapReault(workConnectSelect);
        return workConnectSelect;
    }


    /**
     * 更新工作联系
     * @param workConnectVO
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public WorkConnectVO update(@RequestBody WorkConnectVO workConnectVO) throws BusinessException {
        WorkConnectVO workConnect = maintain.updateWrokConnect(workConnectVO);
        userQuery.tranUserInfoField(new WorkConnectVO[]{workConnect}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return workConnect;
    }

    /**
     * 查询工作联系详情
     * @param pk_workconnect
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/queryById")
    @ResponseBody
    public WorkConnectVO queryById(String pk_workconnect) throws BusinessException {

        if (StringUtils.isEmpty(pk_workconnect)) {
            return null;
        }
        WorkConnectVO workConnectVO = query.selectOne(pk_workconnect);
        wrapReault(workConnectVO);
        return workConnectVO;
    }

    /**
     * 接收功能--单据状态转为已接收
     *
     * @param pk_workconnect
     * @return
     * @throws BusinessException
     */
    // FIXME 这个接口写法可能有问题
    @RequestMapping(value = "/accept")
    @ResponseBody
    public WorkConnectVO acceptBill(String pk_workconnect, String pkReceiver, String suggestion) throws BusinessException {

        WorkConReceiverVO receiverVO = receiverQuery.queryByPkWorkconnectAndPkReceiver(pk_workconnect, pkReceiver);
        // 单个接收人 在子表中查询不到数据, 接收人的信息在主表中 按主表规则更新
        if (receiverVO == null) {
            WorkConnectVO vo = maintain.updateBillStatus(pk_workconnect, null);
            return vo;
        }
        //如果是找到了是主子表的结构
        userQuery.tranUserInfoField(new WorkConReceiverVO[]{receiverVO}, new String[] {WorkConReceiverVO.PK_RECEIVER},
                new String[] {WorkConReceiverVO.RECEIVER_NAME});
        receiverVO.setSuggestion(suggestion);
        receiverVO.setReceiveStatus(WorkConReceiverVO.RECEIVE_STATUS_ACCEPTED);
        receiverVO.setReceivedTime(new Date());
        maintain.updateBillStatus(pk_workconnect, receiverVO);
        WorkConnectVO workConnectVO = query.selectOne(pk_workconnect);
        wrapReault(workConnectVO);
        return workConnectVO;
    }

    /**
     * 封装返回结果
     * @param workConnectSelect
     */
    private void wrapReault(WorkConnectVO workConnectSelect) {
        userQuery.tranUserInfoField(new WorkConnectVO[]{workConnectSelect}, USER_ID_FIELDS, USER_NAME_FIELDS);
        // 旧数据处理
        if (StringUtils.isEmpty(workConnectSelect.getPkReceiver())) {
            WorkConReceiverVO[] receiverVOS = workConnectSelect.getWorkConReceiverVOS();
            userQuery.tranUserInfoField(receiverVOS, new String[]{WorkConReceiverVO.PK_RECEIVER}, new String[]{WorkConReceiverVO.RECEIVER_NAME});
            if(receiverVOS.length > 0){
                List<String> collect = Arrays.stream(receiverVOS).map(WorkConReceiverVO::getReceiverName).collect(Collectors.toList());
                List<String> receivers = Arrays.stream(receiverVOS).filter(vo -> WorkConReceiverVO.RECEIVE_STATUS_UNACCEPT == vo.getReceiveStatus()).map(WorkConReceiverVO::getPkReceiver).collect(Collectors.toList());
                workConnectSelect.setReceiverNames(collect.toArray(new String[0]));
                workConnectSelect.setPkReceivers(receivers.toArray(new String[0]));
            }
        } else {
            userQuery.tranUserInfoField(new WorkConnectVO[]{workConnectSelect}, new String[]{workConnectSelect.PK_RECEIVER}, new String[]{workConnectSelect.RECEIVER_NAME});
        }
    }
    /**
     * 存草稿
     * @param workConnectVO
     * @param response
     * @return
     * @throws BusinessException

     @RequestMapping(value = "/draft")
     @ResponseBody public WorkConnectVO addDraft(WorkConnectVO workConnectVO,
     HttpServletResponse response) throws BusinessException {
     response.setHeader("Access-Control-Allow-Origin", "*");
     // 存草稿，默认为草稿态
     workConnectVO.setBillstatus(WorkConBillStatus.STATUS_DRAFT);
     WorkConnectVO workConnect = maintain.addWorkConnect(workConnectVO);
     userQuery.tranUserInfoField(new WorkConnectVO[]{workConnect}, USER_ID_FIELDS,USER_NAME_FIELDS);
     return workConnect;
     }
     */
}
